package com.cooper.controllers.user;

import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.AppConstants;
import com.cooper.core.JsonResult;
import com.cooper.entity.UserInfo;
import com.cooper.service.core.UserService;
import com.cooper.util.Controllers;
import com.cooper.util.StringUtils;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Post;

public class ResetPasswordController {
	
	@Autowired
	private UserService userService;
	
	@Post
	public Object execute(Invocation inv){
		JsonResult json = new JsonResult();
		String email = inv.getParameter("email");
		String validateCode = inv.getParameter("validateCode");
		String serverValidateCode = (String)inv.getRequest().getSession().getAttribute(AppConstants.VALIDATE_CODE_NAME);
		
		if(StringUtils.isEmpty(serverValidateCode) || StringUtils.isBlank(validateCode)){
			json.setMessage("invalid confirm code, please check it!");
		} else if(StringUtils.isBlank(email) || !StringUtils.isEmail(email)){
			json.setMessage("invalid mail addreses!");
		}else {
			UserInfo user = this.userService.existsUserEmail(email);
			if(null == user || StringUtils.isEmpty(user.getUserName())){
				json.setMessage("user doesn't exists.");
			}else{
				json = this.userService.resetPassword(user.getUserName(), Controllers.getBasePath(inv));
			}
		}
		return json;
	}

}
